'use strict';

//还有我们这里使用了egg-multipart
const md5 = require('md5');
//egg.js Controller
const Controller = require('egg').Controller;
const fs = require('fs')
const path = require('path')

//故名思意 异步二进制 写入流
const awaitWriteStream = require('await-stream-ready').write;
//管道读入一个虫洞。
const sendToWormhole = require('stream-wormhole');


class UploadController extends Controller {
  async index() {
    const ctx = this.ctx;
    const stream = await ctx.getFileStream();
    //新建一个文件名
    const filename = md5(stream.filename) + path
      .extname(stream.filename)
      .toLocaleLowerCase();

    //文件生成绝对路径
    //当然这里这样市不行的，因为你还要判断一下是否存在文件路径
    const target = path.join(this.config.baseDir, 'app/public/uploads', filename);
    const writeStream = fs.createWriteStream(target);
    try {
      //异步把文件流 写入
      await awaitWriteStream(stream.pipe(writeStream));
    } catch (err) {
      //如果出现错误，关闭管道
      await sendToWormhole(stream);
      throw err;
    }
    const data = await ctx.service.web.addimg({ url: 'uploads/' + filename });

    ctx.body = {
      data: 'uploads/' + filename
    }

  }
}

module.exports = UploadController;